const express = require('express');
const router = express.Router();
const menuImportController = require('../controllers/menuImportController');
const { authenticateToken, requireRole } = require('../middleware/auth');
const { handleValidationErrors } = require('../middleware/validation');
const { body, query, param } = require('express-validator');
const rateLimit = require('express-rate-limit');

// 速率限制配置
const uploadRateLimit = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 50, // 临时增加到50次上传（用于测试）
  message: {
    success: false,
    message: '上传频率过高，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

const exportRateLimit = rateLimit({
  windowMs: 5 * 60 * 1000, // 5分钟
  max: 10, // 最多10次导出
  message: {
    success: false,
    message: '导出频率过高，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 验证规则
const exportValidation = [
  query('category_id')
    .optional()
    .isInt({ min: 1 })
    .withMessage('分类ID必须是正整数'),
  query('category_name')
    .optional()
    .isLength({ min: 1, max: 200 })
    .withMessage('分类名称长度必须在1-200字符之间'),
  query('created_after')
    .optional()
    .isISO8601()
    .withMessage('created_after必须是有效的ISO8601日期格式'),
  query('created_before')
    .optional()
    .isISO8601()
    .withMessage('created_before必须是有效的ISO8601日期格式'),
  query('is_available')
    .optional()
    .isBoolean()
    .withMessage('is_available必须是布尔值')
];

const jobListValidation = [
  query('page')
    .optional()
    .isInt({ min: 1 })
    .withMessage('页码必须是正整数'),
  query('limit')
    .optional()
    .isInt({ min: 1, max: 100 })
    .withMessage('每页数量必须在1-100之间'),
  query('status')
    .optional()
    .isIn(['uploaded', 'validating', 'validated', 'committing', 'completed', 'failed'])
    .withMessage('状态值无效'),
  query('import_type')
    .optional()
    .isIn(['menu'])
    .withMessage('导入类型无效')
];

const commitValidation = [
  query('job_id')
    .notEmpty()
    .withMessage('job_id不能为空')
    .isUUID()
    .withMessage('job_id必须是有效的UUID格式')
];

const jobIdValidation = [
  param('id')
    .notEmpty()
    .withMessage('任务ID不能为空')
    .isUUID()
    .withMessage('任务ID必须是有效的UUID格式')
];

/**
 * @swagger
 * components:
 *   schemas:
 *     ImportJob:
 *       type: object
 *       properties:
 *         job_id:
 *           type: string
 *           format: uuid
 *           description: 任务唯一标识
 *         status:
 *           type: string
 *           enum: [uploaded, validating, validated, committing, completed, failed]
 *           description: 任务状态
 *         import_type:
 *           type: string
 *           enum: [menu]
 *           description: 导入类型
 *         original_filename:
 *           type: string
 *           description: 原始文件名
 *         file_size:
 *           type: integer
 *           description: 文件大小（字节）
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         dry_run_result:
 *           type: object
 *           description: Dry-Run验证结果
 *     
 *     DryRunResult:
 *       type: object
 *       properties:
 *         total_rows:
 *           type: integer
 *           description: 总行数
 *         valid_rows:
 *           type: integer
 *           description: 有效行数
 *         error_rows:
 *           type: integer
 *           description: 错误行数
 *         warning_rows:
 *           type: integer
 *           description: 警告行数
 *         new_records:
 *           type: integer
 *           description: 新建记录数
 *         updated_records:
 *           type: integer
 *           description: 更新记录数
 */

/**
 * @swagger
 * /admin/template/menu.xlsx:
 *   get:
 *     summary: 下载菜单导入模板
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 模板文件
 *         content:
 *           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
 *             schema:
 *               type: string
 *               format: binary
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.get('/template/menu.xlsx', 
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  exportRateLimit,
  menuImportController.downloadTemplate.bind(menuImportController)
);

/**
 * @swagger
 * /admin/export/menu:
 *   get:
 *     summary: 导出菜单数据
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: category_id
 *         schema:
 *           type: integer
 *         description: 分类ID过滤
 *       - in: query
 *         name: category_name
 *         schema:
 *           type: string
 *         description: 分类名称过滤
 *       - in: query
 *         name: created_after
 *         schema:
 *           type: string
 *           format: date-time
 *         description: 创建时间起始过滤
 *       - in: query
 *         name: created_before
 *         schema:
 *           type: string
 *           format: date-time
 *         description: 创建时间结束过滤
 *       - in: query
 *         name: is_available
 *         schema:
 *           type: boolean
 *         description: 是否可用过滤
 *     responses:
 *       200:
 *         description: 导出的Excel文件
 *         content:
 *           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
 *             schema:
 *               type: string
 *               format: binary
 *       400:
 *         description: 参数验证失败
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.get('/export/menu',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  exportRateLimit,
  exportValidation,
  handleValidationErrors,
  menuImportController.exportMenu.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/menu:
 *   post:
 *     summary: 上传菜单文件并执行Dry-Run验证
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *                 description: Excel文件 (.xlsx格式)
 *             required:
 *               - file
 *     responses:
 *       200:
 *         description: Dry-Run验证完成
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 job_id:
 *                   type: string
 *                   format: uuid
 *                 statistics:
 *                   $ref: '#/components/schemas/DryRunResult'
 *                 can_commit:
 *                   type: boolean
 *                 has_warnings:
 *                   type: boolean
 *                 error_download_url:
 *                   type: string
 *                   description: 错误文件下载链接（如果有错误）
 *       400:
 *         description: 文件上传失败或格式错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       429:
 *         description: 上传频率过高
 *       500:
 *         description: 服务器错误
 */
router.post('/import/menu',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  uploadRateLimit,
  menuImportController.uploadAndDryRun.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/menu/commit:
 *   post:
 *     summary: 提交导入数据（原子操作）
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 导入任务ID
 *     responses:
 *       200:
 *         description: 导入成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 job_id:
 *                   type: string
 *                   format: uuid
 *                 processed_records:
 *                   type: integer
 *       400:
 *         description: 参数错误或任务状态不允许提交
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 任务不存在
 *       500:
 *         description: 服务器错误
 */
router.post('/import/menu/commit',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  commitValidation,
  handleValidationErrors,
  menuImportController.commitImport.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/job/{id}:
 *   get:
 *     summary: 查询导入任务状态
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: 任务详情
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 job:
 *                   allOf:
 *                     - $ref: '#/components/schemas/ImportJob'
 *                     - type: object
 *                       properties:
 *                         can_rollback:
 *                           type: boolean
 *                         has_snapshot:
 *                           type: boolean
 *                         error_download_url:
 *                           type: string
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 任务不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/import/job/:id',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  jobIdValidation,
  handleValidationErrors,
  menuImportController.getJobStatus.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/errors/{job_id}:
 *   get:
 *     summary: 下载导入错误文件
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: 错误文件
 *         content:
 *           text/csv:
 *             schema:
 *               type: string
 *               format: binary
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 任务或错误文件不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/import/errors/:job_id',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  jobIdValidation,
  handleValidationErrors,
  menuImportController.downloadErrors.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/jobs:
 *   get:
 *     summary: 获取导入任务列表
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 20
 *         description: 每页数量
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [uploaded, validating, validated, committing, completed, failed]
 *         description: 状态过滤
 *       - in: query
 *         name: import_type
 *         schema:
 *           type: string
 *           enum: [menu]
 *           default: menu
 *         description: 导入类型过滤
 *     responses:
 *       200:
 *         description: 任务列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/ImportJob'
 *                 pagination:
 *                   type: object
 *                   properties:
 *                     page:
 *                       type: integer
 *                     limit:
 *                       type: integer
 *                     total:
 *                       type: integer
 *                     pages:
 *                       type: integer
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.get('/import/jobs',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  jobListValidation,
  handleValidationErrors,
  menuImportController.getJobList.bind(menuImportController)
);

/**
 * @swagger
 * /admin/import/categories:
 *   get:
 *     summary: 获取可用分类列表
 *     tags: [Menu Import/Export]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 分类列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                       name:
 *                         type: string
 *                       name_en:
 *                         type: string
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.get('/import/categories',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  menuImportController.getCategories.bind(menuImportController)
);

// ==================== V2 API Routes ====================
// V2 routes with feature flag support

/**
 * @swagger
 * /admin/v2/template/menu.xlsx:
 *   get:
 *     summary: 下载V2菜单导入模板（新三表结构）
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: V2模板文件
 *         content:
 *           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
 *             schema:
 *               type: string
 *               format: binary
 */
router.get('/v2/template/menu.xlsx', 
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  exportRateLimit,
  menuImportController.downloadTemplateV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/export/menu:
 *   get:
 *     summary: 导出V2菜单数据（新三表结构）
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: category_id
 *         schema:
 *           type: integer
 *         description: 分类ID过滤
 *       - in: query
 *         name: category_name
 *         schema:
 *           type: string
 *         description: 分类名称过滤
 *     responses:
 *       200:
 *         description: V2导出文件
 *         content:
 *           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
 *             schema:
 *               type: string
 *               format: binary
 */
router.get('/v2/export/menu',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  exportRateLimit,
  exportValidation,
  handleValidationErrors,
  menuImportController.exportMenuV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/validate:
 *   post:
 *     summary: V2菜单数据验证（新三表结构）
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *                 description: Excel文件
 *     responses:
 *       200:
 *         description: 验证结果
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 job_id:
 *                   type: string
 *                   format: uuid
 *                 validation_result:
 *                   type: object
 */
router.post('/v2/validate',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  uploadRateLimit,
  menuImportController.validateV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/commit:
 *   post:
 *     summary: 提交V2验证通过的数据（新三表结构）
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 验证任务ID
 *     responses:
 *       200:
 *         description: 提交成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 processed_records:
 *                   type: integer
 */
router.post('/v2/commit',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  commitValidation,
  handleValidationErrors,
  menuImportController.commitV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/jobs/{id}:
 *   get:
 *     summary: 查询V2导入任务状态
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: V2任务详情
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 job:
 *                   type: object
 */
router.get('/v2/jobs/:id',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  jobIdValidation,
  handleValidationErrors,
  menuImportController.getJobStatusV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/jobs/{job_id}/validate-report:
 *   get:
 *     summary: 下载V2验证报告
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: 验证报告文件
 *         content:
 *           text/csv:
 *             schema:
 *               type: string
 *               format: binary
 */
router.get('/v2/jobs/:job_id/validate-report',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  param('job_id').isUUID().withMessage('任务ID必须是有效的UUID格式'),
  handleValidationErrors,
  menuImportController.downloadValidateReportV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/jobs/{job_id}/commit-report:
 *   get:
 *     summary: 下载V2提交报告
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: 提交报告文件
 *         content:
 *           text/csv:
 *             schema:
 *               type: string
 *               format: binary
 */
router.get('/v2/jobs/:job_id/commit-report',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  param('job_id').isUUID().withMessage('任务ID必须是有效的UUID格式'),
  handleValidationErrors,
  menuImportController.downloadCommitReportV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/jobs/{job_id}/log:
 *   get:
 *     summary: 下载V2任务日志
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: job_id
 *         required: true
 *         schema:
 *           type: string
 *           format: uuid
 *         description: 任务ID
 *     responses:
 *       200:
 *         description: 任务日志文件
 *         content:
 *           text/plain:
 *             schema:
 *               type: string
 */
router.get('/v2/jobs/:job_id/log',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  param('job_id').isUUID().withMessage('任务ID必须是有效的UUID格式'),
  handleValidationErrors,
  menuImportController.downloadJobLogV2.bind(menuImportController)
);

/**
 * @swagger
 * /admin/v2/images/batch-assign:
 *   post:
 *     summary: 图片批量导入和分配
 *     tags: [Menu Import/Export V2]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               images:
 *                 type: array
 *                 items:
 *                   type: string
 *                   format: binary
 *                 description: 图片文件数组
 *               mapping_file:
 *                 type: string
 *                 format: binary
 *                 description: 图片映射CSV文件（可选）
 *     responses:
 *       200:
 *         description: 批量分配结果
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 job_id:
 *                   type: string
 *                   format: uuid
 *                 processed_count:
 *                   type: integer
 *                 matched_count:
 *                   type: integer
 *                 report_url:
 *                   type: string
 */
router.post('/v2/images/batch-assign',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  uploadRateLimit,
  menuImportController.batchAssignImages.bind(menuImportController)
);

router.get('/v2/jobs/:job_id/normalization-log',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  param('job_id').isUUID().withMessage('任务ID必须是有效的UUID格式'),
  handleValidationErrors,
  menuImportController.downloadNormalizationLogV2.bind(menuImportController)
);

router.get('/v2/jobs/:job_id/category-upsert',
  authenticateToken,
  requireRole(['admin', 'ops_manager']),
  param('job_id').isUUID().withMessage('任务ID必须是有效的UUID格式'),
  handleValidationErrors,
  menuImportController.downloadCategoryUpsertV2.bind(menuImportController)
);

module.exports = router;